import config from './config.js'
class Base {
  constructor() {
    this.baseUrl = config.restUrl;

  }

  request(params) {
    wx.showNavigationBarLoading();
    wx.showLoading();
    const url = this.baseUrl + params.url;
    const method = params.method ? params.method : 'GET'
    wx.request({
      url: url,
      method: method,
      header: params.header,
      data: params.data,
      dataType: 'json',
      success: function(res) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        typeof params.callback === 'function' ? params.callback(res.data) : '';
      },
      fail: function(err) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        wx.showToast({
          title: '获取数据失败，请检查您的网络是否异常！',
        })
        console.log(err);
      }
    });

  }
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  }

  formatTime(time) {
    var t = new Date(time * 1000);
    return t.getFullYear() + '-' + (parseInt(t.getMonth()) + 1) + '-' + t.getDate() + ' ' + t.getHours() + ':' + t.getMinutes();
  }

  login(userInfo, callBacks) {
    var that = this;
    wx.login({
      success: function(res) {
        console.log(res.code)
        if (res.code) {
          that.request({
            url: '/register',
            method: 'POST',
            data: {
              code: res.code,
              nickName: userInfo.nickName,
              gender: userInfo.gender,
              city: userInfo.city,
              province: userInfo.province,
              country: userInfo.country,
              avatarUrl: userInfo.avatarUrl
            },
            callback: function(res) {
              console.log(res)
              callBacks(res)
            }
          })

        } else {
          wx.showToast({
            title: '登陆失败',
          })
        }
      }
    });
  }
}

export default Base;